import sys, os, csv
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(BASE_DIR)
from globally import Databases_Dir, Sourceslists_Dir, Quicklyindex_Dir




class Vague:
    @classmethod
    def search(cls, sourcelistfile):
        # -------- 找出含有关键词相同的包 --------
        csvfile = Quicklyindex_Dir + os.path.split(sourcelistfile)[-1] + '.csv'  # csv文件名
        while True:
            searchstrlist = input("请输入需要模糊搜索的部分单词: ").split()
            fd = open(csvfile, 'r', encoding='UTF-8')
            print(searchstrlist)
            reader = csv.reader(fd)
            first_column = []
            header = next(reader)
            for row in reader:
                first_column.append(row[0])
            for searchstr in searchstrlist:
                keystr = searchstr.lstrip().rstrip()
                for mumber in first_column:
                    if keystr in mumber:
                        print('触发模糊关键词：{} ---- {}'.format(searchstr, mumber))
            fd.close()
            cho = input('====> 是否继续 模糊搜索其他包    [Y/N] \n').lstrip().rstrip()
            if cho == 'y' or cho == 'Y':
                continue
            elif cho == 'n' or cho == 'N':
                break
            else:
                print('Warning！！：选择错误,请重新输入：')


class ChooseSourcelist:
    __sourceslists_dir__ = Sourceslists_Dir
    @classmethod
    # name: read_allsourceslist
    # func: 从Sourceslists_Dir目录中找寻，所有索引文件名列表。
    # return: 所有索引文件名字的列表
    def __read_allsourceslist__(cls) -> list:
        Sourcelist_namelists = []
        for root, dirs, Sourcelist_namelists in os.walk(cls.__sourceslists_dir__):
            Sourcelist_namelists.sort()
        return Sourcelist_namelists

    @classmethod
    # name: menu_show
    # func: 菜单格式化显示所有sources文件名，方便后续选择
    # params: 所有索引文件名字列表 distsnamelists
    def __menu_show__(cls, namelist: list) -> None:
        print('-------- 请选择从哪里搜包，已找到源地址文件 {} 个 --------'.format(len(namelist)))
        for i in range(0, len(namelist)):
            print('# 选项{:2}: {:20} {:10}'.format(i + 1, namelist[i].replace('_' + namelist[i].split('_')[-1], ''), namelist[i].split('_')[-1]))
    @classmethod
    # name: user_choose
    # func: 索引文件选择
    # return: 使用者选择的索引文件全路径的列表
    def __user_choose__(cls, namelists: list) -> str:
        while True:
            userchoose = ""
            # -------- 请用户输入选择的sources.list文件 --------
            choose = input("\n====> 请输入选项序号:  ")
            if not choose.isdigit():    # 数据清洗判断是否为数字
                print('Warning！！: 选择错误，请输入正确选项')
            else:
                choose = int(choose)
                if choose < 0 or choose > len(namelists):
                    print('Warning！！: 选择错误，选择的数字不存在')
                else:
                    userchoose = namelists[choose - 1]  # 如果只用file_list[]，返回值为字符串类型，使用split函数，可以把字符串变成列表
                    break
        # -------- 返回值要求是sources.list文件绝对路径的集合 --------
        re = ""
        re = cls.__sourceslists_dir__ + userchoose
        return re

    # 返回用户选择的源的绝对路径的列表
    @classmethod
    def choose(cls) -> list:
        namelist = cls.__read_allsourceslist__()
        cls.__menu_show__(namelist)
        userchoose = cls.__user_choose__(namelist)
        return userchoose



class Check_Choose:
    databases_dir = Databases_Dir
    @classmethod
    def check_sourcelistfile_exist(cls, sourcelistfile: str) -> None:
        cpuinfo = os.path.basename(sourcelistfile).split('_')[-1]
        # 判断sources.list文件中所需要的packages文件是否都存在。不存在直接退出程序
        blocks = cls.__file2blocks__(sourcelistfile)
        for block in blocks:
            dirpath = cls.databases_dir + block[0].split('//')[-1] + '/dists/' + block[1] + '/' + block[2] + '/binary-' + cpuinfo + '/Packages'
            if not os.path.exists(dirpath):
                print('Error: 缺少Packages文件，请先进行源更新')
                sys.exit(0)
            else:
                pass
        # -------- 判断快速索引文件是否存在，不存在就退出程序 --------
        csvfile = Quicklyindex_Dir + os.path.split(sourcelistfile)[-1] + '.csv'  # csv文件名
        if not os.path.exists(csvfile):
            print('Error: 快速索引文件不存在，请先更新源')

    @classmethod
    def __file2blocks__(cls, sourceslistfile):
        def read_sourceslistfile() -> list:
            needlines = []
            f = open(sourceslistfile, 'r', encoding='UTF-8')
            while True:
                info = f.readline()  # 逐行读取 sources.list 文件
                if info:  # 判断是否读取到文件结尾
                    info = info.rstrip().lstrip()
                    if info and not info.startswith('#'):  # 剔除读取到的空行
                        needlines.append(info)
                else:  # 文件读取到最后了，退出
                    break
            f.close()
            return needlines

        def generate_datablocks(needlines) -> list:
            re = []
            for needline in needlines:
                info = needline.split()
                while info:
                    mumber = info[0]
                    if mumber.startswith('http'):
                        break
                    else:
                        info.remove(mumber)
                # print(returninfo)  # ['http://archive.kylinos.cn/kylin/KYLIN-ALL', '10.1', 'main', 'universe', 'multiverse', 'restricted']
                url_head = info.pop(0)  # 结果：http://archive.kylinos.cn/kylin/KYLIN-ALL
                product_info = info.pop(0)  # 结果： 10.1
                repo_list = info  # 结果： ['main', 'universe', 'multiverse', 'restricted']
                for repo in repo_list:  # 列出所有的库
                    block = [url_head, product_info, repo]
                    re.append(block)
            return re

        filelines = read_sourceslistfile()  # 读取sources.list 文件
        if filelines:
            blocks = generate_datablocks(filelines)  # 将文件转化成datablocks形式的列表
            # datablock：['http://archive.kylinos.cn/kylin/KYLIN-ALL', '10.1-2203-updates', 'multiverse']
            return blocks
        else:
            print("文件为空，请检查文件是否正确 path=", sourceslistfile)
            sys.exit(0)
